package com.ytjj.qmyx.data.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ytjj.common.dto.mqdto.OrderRecordDto;
import com.ytjj.qmyx.data.constants.MongoCollectionNameConstants;
import com.ytjj.qmyx.data.mapper.StatisticsMapper;
import com.ytjj.qmyx.data.model.mongo.OrderRecordStatistics;
import com.ytjj.qmyx.data.model.mongo.PageStatistics;
import com.ytjj.qmyx.data.model.mongo.ProductStatistics;
//import com.ytjj.qmyx.data.service.KafkaSendService;
import com.ytjj.qmyx.data.service.OrderRecordService;
import com.ytjj.qmyx.mall.model.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 *  *
 **/
@Slf4j
@Service
public class OrderRecordServiceImpl implements OrderRecordService {

    @Resource
    private MongoTemplate mongoTemplate;

//    @Autowired
//    private KafkaSendService kafkaSendService;

    @Resource
    private StatisticsMapper statisticsMapper;

    @Override
    public void addRecord(OrderRecordDto recordDto) {
        OrderRecordStatistics orderRecordStatistics=new OrderRecordStatistics();
        BeanUtils.copyProperties(recordDto, orderRecordStatistics);
        String collection = MongoCollectionNameConstants.ORDER_RECORD;
        Query query = Query.query(Criteria.where("orderInfoId").is(recordDto.getOrderInfoId()));
        OrderRecordStatistics savedOrderRecord=mongoTemplate.findOne(query,OrderRecordStatistics.class,collection);
        if (org.apache.commons.lang.StringUtils.isEmpty(orderRecordStatistics.getSeq_id())) {
            orderRecordStatistics.setSeq_id(UUID.randomUUID().toString().replace("-", ""));
        }
        if (org.apache.commons.lang.StringUtils.isEmpty(orderRecordStatistics.getCur_date())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            orderRecordStatistics.setCur_date(sdf.format(new Date()));
        }
        if (null == orderRecordStatistics.getDynamicId() && null != recordDto.getDynamicId()) {
            orderRecordStatistics.setDynamicId(String.valueOf(recordDto.getDynamicId()));
        }
        try {
            if (org.apache.commons.lang.StringUtils.isEmpty(savedOrderRecord.getSeq_id())) {
                savedOrderRecord.setSeq_id(UUID.randomUUID().toString().replace("-", ""));
            }
            if (org.apache.commons.lang.StringUtils.isEmpty(savedOrderRecord.getCur_date())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                savedOrderRecord.setCur_date(sdf.format(new Date()));
            }
        } catch (Exception e) {

        }

        if(savedOrderRecord!=null){
            log.debug("savedOrderRecord={}", savedOrderRecord);
            if(null != recordDto.getIsAddress() && 1 == recordDto.getIsAddress()) {//收到有地址订单记录
                if(savedOrderRecord.getIsAddress() == null || savedOrderRecord.getIsAddress() ==0) {//存在无地址订单
                    savedOrderRecord.setIsAddress(1);
                    mongoTemplate.upsert(Query.query(Criteria.where("orderInfoId").is(recordDto.getOrderInfoId())), Update.update("isAddress", 1), collection);
                    sendToKafka(savedOrderRecord);
                }
            }
            if (null != recordDto.getIsPay() && 1 == recordDto.getIsPay()) {//收到已支付订单记录
                if (savedOrderRecord.getIsPay() == null || savedOrderRecord.getIsPay() == 0) {//存在未支付订单
                    savedOrderRecord.setPayTime(recordDto.getPayTime());
                    savedOrderRecord.setIsPay(1);
                    mongoTemplate.upsert(Query.query(Criteria.where("orderInfoId").is(recordDto.getOrderInfoId())), Update.update("isPay", 1).set("payTime",recordDto.getPayTime()), collection);
                    sendToKafka(savedOrderRecord);
                }
            }
        }else{//不存在订单号orderNo的记录
            log.debug("===orderRecordStatistics==={}", orderRecordStatistics);
            mongoTemplate.save(orderRecordStatistics);
            sendToKafka(orderRecordStatistics);
        }
    }

    private void sendToKafka(OrderRecordStatistics orderRecordStatistics){
//        try{
//            log.debug("sendOrderRecord={}", JSONObject.toJSONString(orderRecordStatistics));
//            boolean sendStatus=kafkaSendService.sendOrderRecordMsg(JSONObject.toJSONString(orderRecordStatistics));
//            log.debug("sendOrderRecordStatus={}",true);
//        }catch (Exception e){
//            log.error("发送到kafka错误",e);
//        }
    }

    @Override
    public void sendHistoryDataToKafka(String startTime) {
        if (StringUtils.isEmpty(startTime)) {
            startTime = "2021-03-01";//开始时间
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(startTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar end_calendar = Calendar.getInstance();//new一个Calendar类,把Date放进去
        end_calendar.setTime(new Date());
        end_calendar.add(Calendar.DATE, -1);//实现日期加一操作,也就是明天
        for (long d = cal.getTimeInMillis(); d <= end_calendar.getTime().getTime(); d = get_D_Plaus_1(cal)) {
            String collection = MongoCollectionNameConstants.ORDER_RECORD + sdf.format(d);
            Criteria criteria = new Criteria() ;
            Query query = Query.query(criteria);
            List<OrderRecordDto> saveOrderRecordDtoList = mongoTemplate.find(query, OrderRecordDto.class, collection);

            String productCollection = MongoCollectionNameConstants.PRODUCT + sdf.format(d);
            List<ProductStatistics> productList = mongoTemplate.find(query, ProductStatistics.class, productCollection);

            saveOrderRecordDtoList.forEach(item -> {
                Orders orders = statisticsMapper.findOrdersById(item.getOrderId());
                if (null != orders) {
                    item.setUserId(orders.getUserId());
                    item.setPayType(orders.getPayType());
                    item.setPaySource(orders.getPaySource());
                    item.setCity(orders.getCity());
                    item.setArea(orders.getArea());
                    item.setAddress(orders.getAddress());
                    item.setProvince(orders.getProvince());
                    item.setUserAddress(orders.getUserAddress());
                    item.setPayTime(orders.getPayTime());
                    item.setUpdateTime(orders.getUpdateTime());
                }
                if (item.getIsPay()!=null&&item.getIsPay()==1){
                    item.setPayTime(item.getUpdateTime());
                }

//                boolean sendStatus=kafkaSendService.sendOrderRecordHistoryMsg(JSONObject.toJSONString(item));
            });

        }
    }

    public static long get_D_Plaus_1(Calendar c) {
        c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 1);
        return c.getTimeInMillis();
    }

    private void sendToKafkaByOrderHistory(OrderRecordStatistics orderRecordStatistics){
//        try{
//            log.debug("sendOrderRecordHistory={}", JSONObject.toJSONString(orderRecordStatistics));
//            boolean sendStatus = kafkaSendService.sendOrderRecordHistoryDeleteMsg(JSONObject.toJSONString(orderRecordStatistics));
//            log.debug("sendOrderRecordHistoryStatus={}",true);
//        }catch (Exception e){
//            log.error("发送到order_record_history_kafka错误",e);
//        }
    }

    @Override
    public void addRecordByHistory(OrderRecordDto recordDto) {
        OrderRecordStatistics orderRecordStatistics=new OrderRecordStatistics();
        BeanUtils.copyProperties(recordDto, orderRecordStatistics);
        String collection = MongoCollectionNameConstants.ORDER_RECORD;
        Query query = Query.query(Criteria.where("orderInfoId").is(recordDto.getOrderInfoId()));
        OrderRecordStatistics savedOrderRecord=mongoTemplate.findOne(query,OrderRecordStatistics.class,collection);
        if (org.apache.commons.lang.StringUtils.isEmpty(orderRecordStatistics.getSeq_id())) {
            orderRecordStatistics.setSeq_id(UUID.randomUUID().toString().replace("-", ""));
        }
        if (org.apache.commons.lang.StringUtils.isEmpty(orderRecordStatistics.getCur_date())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            orderRecordStatistics.setCur_date(sdf.format(new Date()));
        }
        if (null == orderRecordStatistics.getDynamicId() && null != recordDto.getDynamicId()) {
            orderRecordStatistics.setDynamicId(String.valueOf(recordDto.getDynamicId()));
        }
        try {
            if (org.apache.commons.lang.StringUtils.isEmpty(savedOrderRecord.getSeq_id())) {
                savedOrderRecord.setSeq_id(UUID.randomUUID().toString().replace("-", ""));
            }
            if (org.apache.commons.lang.StringUtils.isEmpty(savedOrderRecord.getCur_date())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                savedOrderRecord.setCur_date(sdf.format(new Date()));
            }
        } catch (Exception e) {

        }

        if(savedOrderRecord!=null){
            log.info("savedOrderRecord={}", savedOrderRecord);
            if(null != recordDto.getIsAddress() && 1 == recordDto.getIsAddress()) {//收到有地址订单记录
                if(savedOrderRecord.getIsAddress() == null || savedOrderRecord.getIsAddress() ==0) {//存在无地址订单
                    savedOrderRecord.setIsAddress(1);
                    mongoTemplate.upsert(Query.query(Criteria.where("orderInfoId").is(recordDto.getOrderInfoId())), Update.update("isAddress", 1), collection);
                    sendToKafkaByOrderHistory(savedOrderRecord);
                }
            }
            if (null != recordDto.getIsPay() && 1 == recordDto.getIsPay()) {//收到已支付订单记录
                if (savedOrderRecord.getIsPay() == null || savedOrderRecord.getIsPay() == 0) {//存在未支付订单
                    savedOrderRecord.setPayTime(recordDto.getPayTime());
                    savedOrderRecord.setIsPay(1);
                    mongoTemplate.upsert(Query.query(Criteria.where("orderInfoId").is(recordDto.getOrderInfoId())), Update.update("isPay", 1).set("payTime",recordDto.getPayTime()), collection);
                    sendToKafkaByOrderHistory(savedOrderRecord);
                }
            }
        }else{//不存在订单号orderNo的记录
            log.info("===orderRecordStatistics==={}", orderRecordStatistics);
            mongoTemplate.save(orderRecordStatistics);
            sendToKafkaByOrderHistory(orderRecordStatistics);
        }
    }


    public static void main(String[] args) {
        String startTime = "2021-03-01";//开始时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(startTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(get_D_Plaus_1(cal));
        System.out.println(sdf.format(cal.getTime()));


        Calendar calendar = Calendar.getInstance();//new一个Calendar类,把Date放进去
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -1);//实现日期加一操作,也就是明天
        System.out.println(sdf.format(calendar.getTime()));
    }
}
